package com.ciaojian.client.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ciaojian.client.service.CouponCodeServiceImpl;
import com.ciaojian.client.service.CouponServiceImpl;
import com.ciaojian.client.service.ExchangeCodeServiceImpl;
import com.ciaojian.core.enums.business.CouponCodeOriginEnum;
import com.ciaojian.core.mapper.CouponCodeMapper;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.vo.CouponVo;
import com.ciaojian.core.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * @author Atlakyn
 */
@Api(tags = "优惠券")
@RestController
@RequestMapping("/coupon")
public class CouponController {
    @Resource
    private CouponServiceImpl couponService;
    @Resource
    private CouponCodeMapper couponCodeMapper;
    @Resource
    private ExchangeCodeServiceImpl exchangeCodeService;
    @Resource
    private CouponCodeServiceImpl couponCodeService;

    @ApiOperation("根据ID获取优惠券详情")
    @ApiResponses({@ApiResponse(code = 200, message = "SUCCESS", response = Coupon.class)})
    @GetMapping("/{id}")
    public Result getCoupon(@PathVariable Integer id) {
        return Result.ok(new Coupon().selectById(id));
    }


    /**
     * 检查抖音券是否发放 无则直接发放
     */
//    @GetMapping("/checkDyCoupon")
//    public Result checkDyCoupon(Integer userId){
//        return couponService.checkDyCoupon(userId);
//    }

    /**
     * 我的优惠券列表
     *
     * @param userId 用户 id
     * @return 用户优惠列表
     */
    @GetMapping("/code")
    public Result getCouponCode(Integer userId, Integer orderId) {
        Assert.notNull(userId, "userId 不能为空");
        Order order = new Order().selectById(orderId);
        HashMap<String, List<CouponVo>> couponCode;
        // 订单价格不为空,按订单价格查询达到门槛的优惠券
        if (order != null && order.getTotal() != null) {
            String total = order.getTotal().toString();
            LambdaQueryWrapper<HaircutService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HaircutService::getTitle, order.getType());
            HaircutService haircutService = new HaircutService().selectOne(lambdaQueryWrapper);
            Assert.notNull(haircutService, "没有此服务");
            int dayOfWeek = DateUtil.dayOfWeek(new Date());
            // 因为 DateUtil.dayOfWeek 中是因周日开始, 为了直观理解把周日改成7,其他时间都-1
            dayOfWeek = dayOfWeek == 1 ? 7 : dayOfWeek - 1;
            couponCode = couponService.getCouponCode(userId, total, order.getStoreId(), haircutService.getId(), dayOfWeek);
        } else {
            couponCode = couponService.getCouponCode(userId, null, null, null, null);
        }
        return Result.ok(couponCode);
    }

    /**
     * 兑换券优化接口
     */
    @PostMapping("/exchangeNew")
    public Result exchangeCoupon(@RequestBody String str) {
        JSONObject jsonObject = JSON.parseObject(str);
        Date now = new Date();
        Integer userId = jsonObject.getInteger("userId");
        String exchange = jsonObject.getString("exchange");
        Assert.notNull(userId, "userId 不能为空");
        Assert.notNull(exchange, "兑换码 不能为空");
        ExchangeCode exchangeCode = exchangeCodeService.getByExchangeCode(exchange);
        Assert.notNull(exchangeCode, "兑换码不存在");
        exchangeCode.setUserId(userId);
        exchangeCode.setStatus(1);
        exchangeCode.setUseTime(new Date());
        // 根据兑换码获取券码
        CouponCode couponCode = couponCodeMapper.getByExchange(exchange);
        if (couponCode != null) {
            Assert.isTrue(couponCode.getUserId() == null, "兑换码已被兑换");
            Assert.isTrue(couponService.getCouponExpiredTime(couponCode.getCouponId()).after(now), "优惠券已过期");
            Coupon coupon = couponService.getById(couponCode.getCouponId());//券信息
            if (coupon.getDateType() == 0) {//固定到期时间
                couponCode.setExpiredTime(coupon.getEndTime());
            } else {//领取后到期
                couponCode.setExpiredTime(DateUtil.offsetDay(now, coupon.getSameDay()));
            }
            couponCode.setUserId(userId);
            couponCode.setStatus(1);
            couponCode.setOrigin(CouponCodeOriginEnum.CODE_EXCHANGE);
            couponCodeService.saveOrUpdate(couponCode);
            exchangeCodeService.saveOrUpdate(exchangeCode);
            return Result.ok("兑换成功");
        } else {
            return Result.error("兑换码不存在");
        }
    }
}
